<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use FroalaEditor\Image;
use FroalaEditor\Video;
use FroalaEditor\File;
use App\Admin\Models\FileModel;

class FileController extends Controller
{
    /**
     * uploadImages
     */
    public function uploadImages()
    {
        $user = \Admin::user();

        try {
            // 在文件上传处理之前先获取参数，避免触发文件处理导致临时文件访问错误
            $contentId = (int)request()->input('content_id', 0);
            $contentType = (int)request()->input('content_type', 0);
            
            $response   = Image::upload('/upload/images/' . date('Y') . '/' . date('m') . '/' . date('d') . '/', [
                'fieldname' => 'froala_image'
            ]);
            $return     = stripslashes(json_encode($response));
            $returnData = json_decode($return, true);

            // 上传成功后，保存到file文件表中
            if (!empty($returnData['link']) && !empty($_FILES['froala_image'])) {
                // Get filename.
                $temp = explode(".", $_FILES['froala_image']['name']);

                // Get extension.
                $extension = end($temp);

                FileModel::create([
                    'file_name'        => $_FILES['froala_image']['name'],
                    'file_path'        => $returnData['link'],
                    'file_source_path' => $returnData['link'],
                    'file_url'         => $returnData['link'],
                    'file_ext'         => $extension,
                    'file_size'        => $_FILES['froala_image']['size'],
                    'content_id'       => $contentId,
                    'content_type'     => $contentType,
                    'user_id'          => $user->id
                ]);
            }

            echo $return;
            exit;
        } catch (Exception $e) {
            http_response_code(404);
        }
    }

    /**
     * uploadVideos
     */
    public function uploadVideos()
    {
        try {
            $response = Video::upload('/upload/videos/' . date('Y') . '/' . date('m') . '/' . date('d') . '/', [
                'fieldname' => 'froala_video'
            ]);

            // 上传成功后，保存到file文件表中 TODO

            echo stripslashes(json_encode($response));
            exit;
        } catch (Exception $e) {
            http_response_code(404);
        }
    }

    /**
     * uploadFiles
     */
    public function uploadFiles()
    {
        try {
            $response = File::upload('/upload/files/' . date('Y') . '/' . date('m') . '/' . date('d') . '/', [
                'fieldname'  => 'froala_file',
                'validation' => null // \FroalaEditor\Utils\Utils 有这个判断if (is_array($validation))，文件上传不限制格式，所以这里将验证去掉
            ]);

            // 上传成功后，保存到file文件表中 TODO

            echo stripslashes(json_encode($response));
            exit;
        } catch (Exception $e) {
            http_response_code(404);
        }
    }
}
